#include <input_manager.h>
#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <unistd.h>

/*
socker
connect
send/recv
*/
#define SERVER_PORT 8888

static int g_iSocketServer;

static int NetinputGetInputEvent(pInputEvent ptInputEvent)
{
	struct sockaddr_in tSocketClientAddr;
	unsigned int iAddrLen;
	int iRecvLen;
	char aRecvBuf[1000];
    iAddrLen = sizeof(struct sockaddr);
    iRecvLen =  recvfrom(g_iSocketServer, aRecvBuf, 999, 0,
                    (struct sockaddr *)&tSocketClientAddr, &iAddrLen);
    if(iRecvLen > 0)
    {
    	printf("get buf : %s \n", aRecvBuf);
        aRecvBuf[iRecvLen] = '\0';
        //printf("Get Msg from %s : %s",inet_ntoa(tSocketClientAddr.sin_addr),ucRecvBuf);
		ptInputEvent->iType		= INPUT_TYPE_NET;
		strncpy(ptInputEvent->str, aRecvBuf, 1000);
		ptInputEvent->str[999] = '\0';
		gettimeofday(&ptInputEvent->tTime, NULL);
		return 0;
	}
	return -1;
}	
static int NetinputDeviceInit(void)
{
	
    int iRet;
    struct sockaddr_in tSocketServerAddr; //服务端ipv4地址

    g_iSocketServer = socket(AF_INET, SOCK_DGRAM, 0);	//创建一个UDP Socket		AF_INET：ipv4协议； SOCK_DGRAM：UDP传输协议 0：自动选择协议

	//配置服务器地址
	tSocketServerAddr.sin_family        = AF_INET;				//协议为ipv4
    tSocketServerAddr.sin_port          = htons(SERVER_PORT); /*host to net,short*/
	
	tSocketServerAddr.sin_addr.s_addr   = INADDR_ANY;		/*	sin_addr.s_addr：指定套接字要绑定的本地IP地址。
															 *	INADDR_ANY：绑定到所有本地网络接口（0.0.0.0），接收来自任何接口的数据
															 */
    memset(tSocketServerAddr.sin_zero,0,8);
	//将Socket绑定到指定的ip和
    iRet = bind(g_iSocketServer, (const struct sockaddr *)&tSocketServerAddr,sizeof(struct sockaddr));
	//绑定失败
    if(-1 == iRet)
    {
        printf("bind error\n");
		close(g_iSocketServer);
        return -1;
    }
	return 0;
}
static int NetinputDeviceExit(void)
{
	close(g_iSocketServer);
	return 0;
}

struct InputDevice g_tNetinputDev = {
	.name = "touchscreen",
	.GetInputEvent 	=  NetinputGetInputEvent,
	.DeviceInit 	= NetinputDeviceInit,
	.DeviceExit 	= NetinputDeviceExit,
	.ptNext 		= NULL,
};

void RegisterNetinputDev(void)
{
	RegisterInputDevice(&g_tNetinputDev);
}

//unit test
#if 0

int main(int argc, char **argv)
{
	InputEvent event;
	int ret;

	g_tNetinputDev.DeviceInit();
	
	while(1)
	{
		ret = g_tNetinputDev.GetInputEvent(&event);
		if(ret)
		{
			printf("GetInputEvent err\n");
			return -1;
		}
		else
		{
			printf("Type : %d\n", event.iType);
			printf("str : %s\n", event.str);
		}
	}
	return 0;
}

#endif

